package com.myrpc.transfer.transport.socket;

import com.myrpc.exception.MyRpcException;
import com.myrpc.register.ServiceDiscovery;
import com.myrpc.register.nacos.NacosServiceDiscovery;
import com.myrpc.transfer.dto.RpcRequest;
import com.myrpc.transfer.transport.RpcRequestTransport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 套接字Socket 请求调用客户端实现
 */
@Component(value = "SocketRpcRequestClient")
@DependsOn({"NacosServiceDiscovery"})
public class SocketRpcRequestClient implements RpcRequestTransport {
    @Autowired
    private ServiceDiscovery serviceDiscovery;

    /**
     * 发送请求并调用
     *
     * @param rpcRequest 请求实体类
     * @return 服务器数据
     */
    @Override
    public Object sendRpcRequest(RpcRequest rpcRequest) throws MyRpcException {
        //得到目标微服务地址
        InetSocketAddress address = serviceDiscovery.discoveryService(rpcRequest);
        try (Socket socket = new Socket()) {
            //套接字连接
            socket.connect(address);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            //发送请求
            objectOutputStream.writeObject(rpcRequest);
            //等待回复
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            return objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new MyRpcException("远程调用失败" + e);
        }
    }
}
